package com.zzl.study.ssh;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.SCPOutputStream;
import ch.ethz.ssh2.Session;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;

/**
 * @author: zhangzl
 * @date: 2022/10/21 19:55
 * @version: 1.0
 * @description: Java使用ssh连接Linux服务器执行命令测试代码
 */
public class Main {

    public static void main(String[] args) throws Exception {
        Connection connection = new Connection("192.168.85.189", 22);
        connection.connect();
        boolean authenticate = connection.authenticateWithPassword("root", "123456");
        if (authenticate) {
            System.out.println("连接成功!");
            Session session = connection.openSession();
            // 这个方法是不能被重复调用的，要想执行多条命令的话，需要对命令进行合并，以“;”分割
            session.execCommand("cd /opt/demo;mv abc.txt abc.txt.bak");
            SCPClient scpClient = connection.createSCPClient();
            File file = new File("/opt/demo/abc.txt");
            try (FileInputStream fileInputStream = new FileInputStream(file);
                 SCPOutputStream scpOutputStream = scpClient.put(file.getName(), file.length(), "/opt/demo", "0664")) {
                // 文件能拷贝过去的前提是目标服务器上文件目录都存在!!!
                IOUtils.copy(fileInputStream, scpOutputStream);
                System.out.println("远程拷贝文件成功!");
            } catch (Exception e) {
                System.err.println("远程拷贝文件失败!");
                e.printStackTrace();
            }
            session.close();
        } else {
            System.err.println("连接失败!");
        }
        connection.close();
    }

}
